package com.mr.biz.support;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import ognl.OgnlException;

import com.mr.utils.ClassPathFreeMarkerUtils;
import com.mr.utils.JacksonUtils;
import com.mr.utils.OgnlUtils;

import freemarker.template.TemplateException;

/**
 * @author Alex
 * 
 */
public class AbstractRepository implements Repository {

	protected Map<String, Object> extractParams(DefaultRequest request) throws IOException {
		String jsonData = request.getJsonData();
		return JacksonUtils.readFromStr(jsonData);
	}

	protected OgnlUtils.Parser getRequestParser(Request request) throws IOException {
		Map<String, Object> map = extractParams((DefaultRequest) request);
		return OgnlUtils.newParser(map);
	}

	protected String getPackagePath() {
		String packagePath = getClass().getPackage().getName();
		return packagePath.replaceAll("\\.", "/");
	}

	protected Response generateResponse(Object dataModel) throws IOException {
		String data = JacksonUtils.convertToJsonStr(dataModel);
		return new DefaultResponse(data);
	}

	protected Response generateResponseWithFreeMarker(Map<String, Object> root, String responseName)
			throws IOException, TemplateException {
		String templatePath = getPackagePath() + "/" + responseName + ".ftl";

		String data = ClassPathFreeMarkerUtils.generate(templatePath, root);

		return newDefaultResponse(data);
	}

	private Response newDefaultResponse(String data) {
		DefaultResponse response = new DefaultResponse();
		response.setJsonData(data);

		return response;
	}

	protected Response newDefaultResponse(Map<String, Object> root) throws Exception {
		DefaultResponse response = new DefaultResponse();
		response.setMapData(root);
		return response;
	}

	protected String getId(OgnlUtils.Parser parser) throws OgnlException, IOException {
		return parser.parse("id", String.class);
	}

	protected Map<String, Object> createRoot() {
		return new HashMap<String, Object>();
	}
}
